package com.fs.web.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.baseMapper.UserMapper;
import com.fs.common.baseMapper.UserRoleMapper;
import com.fs.common.pojo.User;
import com.fs.common.pojo.UserRole;
import com.fs.common.utils.BaseUtile;
import com.fs.web.base.annotation.SystemControllerLog;
import com.fs.web.base.enums.CodeEnum;
import com.fs.web.base.enums.OperationTypeEnum;
import com.fs.web.base.param.SysConstant;
import com.fs.web.base.utils.ApplicationUtils;
import com.fs.web.base.utils.AuthorityUtils;
import com.fs.web.base.utils.EncodeUtil;
import com.fs.web.base.utils.PageHeper;
import com.fs.web.base.vo.DataGrid;
import com.fs.web.base.vo.JsonResponse;
import com.fs.web.base.vo.LoginUser;
import com.fs.web.base.vo.SysPath;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author ACE
 * @desc 用户controller
 * @creationTime 2019-04-11 15:26
 * @projectName weixinframe
 * @packageName com.fs.web.base.controller
 */
@Slf4j
@Controller
@RequestMapping("/console/user/rewrite")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @GetMapping("{modleName}/index")
    public String index(@PathVariable String modleName){
        return SysPath.BACK_PATH.concat("/user/").concat(modleName);
    }

    @RequestMapping("/toConfig")
    public String toConfig(){
        return SysPath.BACK_PATH.concat("/user/config");
    }

    @ResponseBody
    @RequestMapping("/confirmPassword")
    public JsonResponse confirmPassword(){
        try {
            User user = ApplicationUtils.getUser().getUser();
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String password = map.get("password").toString();
            password = EncodeUtil.getSignAndMD5(password);
            if(password.equals(user.getPwd())){
                return JsonResponse.success(true);
            }else{
                return JsonResponse.success(false);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @ResponseBody
    @RequestMapping("/list")
    public JsonResponse list(HttpServletRequest request){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            Page page = PageHeper.pageRequest(request);
            map = AuthorityUtils.getAuthorityMap(map);
            Page<User> list = userMapper.findList(page, map);
            return JsonResponse.success(DataGrid.gridBuilder(list));
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @SystemControllerLog(description = "重置密码",type = OperationTypeEnum.UPDATE)
    @ResponseBody
    @RequestMapping("/resetPwd")
    public JsonResponse resetPwd(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String id = map.get("id").toString();
            User user = userMapper.selectById(id);
            user.setPwd(EncodeUtil.getSignAndMD5(user.getAccount()));
            userMapper.updateById(user);
            return JsonResponse.success("密码重置成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @SystemControllerLog(description = "修改密码",type = OperationTypeEnum.UPDATE)
    @ResponseBody
    @RequestMapping("/updatePwd")
    public JsonResponse updatePwd(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String userId = ApplicationUtils.userId();
            String oldPwd = map.get("oldPwd").toString();
            String newPwd = map.get("newPwd").toString();
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("id",userId);
            wrapper.eq("pwd", EncodeUtil.getSignAndMD5(oldPwd));
            User user = userMapper.selectOne(wrapper);
            if(null == user){
                return JsonResponse.error("原密码错误");
            }
            user.setPwd(EncodeUtil.getSignAndMD5(newPwd));
            user.setIsUpdatePwd(0);
            userMapper.updateById(user);
            LoginUser user1 = ApplicationUtils.getUser();
            user1.setUser(user);
            ApplicationUtils.getSession().setAttribute(SysConstant.SESSION_CONSOLE_USER, user1);
            return JsonResponse.success("修改密码成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @ResponseBody
    @RequestMapping("/addDecoder")
    public JsonResponse addDecoder(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String id = map.get("id").toString();
            User user = userMapper.selectById(id);
            user.setDecoder(BaseUtile.generatePassword(8));
            userMapper.updateById(user);
            return JsonResponse.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @ResponseBody
    @RequestMapping("/prohibit")
    public JsonResponse prohibit(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String id = map.get("id").toString();
            String userStatus = map.get("userStatus").toString();
            User user = userMapper.selectById(id);
            user.setUserStatus(userStatus);
            userMapper.updateById(user);
            return JsonResponse.success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @ResponseBody
    @RequestMapping("/config")
    public JsonResponse config(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String id = map.get("id").toString();
            String roleId = map.get("roleId").toString();
            if(StringUtils.isNoneBlank(id) && StringUtils.isNoneBlank(roleId)){
                QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",id);
                UserRole userRole = userRoleMapper.selectOne(wrapper);
                if(null != userRole){
                    if(!userRole.getRoleId().equals(roleId)){
                        userRole.setRoleId(roleId);
                        userRoleMapper.updateById(userRole);
                    }
                }else{
                    userRole = new UserRole();
                    userRole.setUserId(id);
                    userRole.setRoleId(roleId);
                    userRoleMapper.insert(userRole);
                }
            }
            return JsonResponse.success("授权成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 获取当前登录用户最新信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/getLoginUser")
    public JsonResponse getLoginUser(){
        User user = userMapper.selectById(ApplicationUtils.userId());
        return JsonResponse.success(user);
    }

    @ResponseBody
    @RequestMapping("/delete")
    public JsonResponse delete(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String id = map.get("id").toString();
            QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",id);
            List<UserRole> userRoles = userRoleMapper.selectList(wrapper);
            if(!CollectionUtils.isEmpty(userRoles)){
                for (UserRole userRole : userRoles) {
                    userRoleMapper.deleteById(userRole.getId());
                }
            }
            userMapper.deleteById(id);
            return JsonResponse.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }
}
